package Project;

import Hulppakket.*;

// NOTE: To ease the storage cost, perhaps a separate TriangleGroup class can be implemented which stores only verteces,..
public class Triangle extends Surface{
	private Point3f p1;
	private Point3f p2;
	private Point3f p3;

	public Triangle(Point3f p1p, Point3f p2p, Point3f p3p, Color3f colorc) {
		p1=p1p;
		p2=p2p;
		p3=p3p;
		this.setColor(colorc);
	}
	@Override
	boolean hit(Ray r, double t0, double t1, Hitrecord rec) {
		float a = getP1().x-getP2().x;
		float b = getP1().y-getP2().y;
		float c = getP1().z-getP2().z;
		float d = getP1().x-getP3().x;
		float e = getP1().y-getP3().y;
		float f = getP1().z-getP3().z;
		float g = r.getDirection().x;
		float h = r.getDirection().y;
		float i = r.getDirection().z;
		float j = getP1().x-r.getOrigin().x;
		float k = getP1().y-r.getOrigin().y;
		float l = getP1().z-r.getOrigin().z;
		float eiminhf = e*i - h*f;
		float gfmindi = g*f - d*i;
		float dhmineg = d*h - e*g;
		float M = a*eiminhf+b*gfmindi+c*dhmineg;
		if(M==0) {
			System.out.println("Determinant zero = no unique solution!!");
			return false;
		}
		float t = -1*(f*(a*k-j*b)+e*(j*c-a*l)+d*(b*l-k*c))/M;
		if(t < t0 || t > t1) {
			return false;
		}
		float gamma = (i*(a*k-j*b)+h*(j*c-a*l)+g*(b*l-k*c))/M;
		if(gamma < 0 || gamma > 1) {
			return false;
		}
		float beta = (j*eiminhf+k*gfmindi+l*dhmineg)/M;
		if(beta < 0 || beta > (1-gamma)) {
			return false;
		}
		rec.t = t;
		rec.intersection = Point3f.Plus(r.getOrigin(), r.getDirection().multiply(t));
		// Formule boek pagina 48
		rec.normal = Vector3f.cross(Point3f.Min(getP2(), getP1()), Point3f.Min(getP3(), getP1())).normalise();
		rec.color = this.getColor();
		return true;
	}

	@Override
	Box boundingbox() {
		// TODO Auto-generated method stub
		return null;
	}

	public Point3f getP1() {
		return p1;
	}

	public void setP1(Point3f p1) {
		this.p1 = p1;
	}

	public Point3f getP2() {
		return p2;
	}

	public void setP2(Point3f p2) {
		this.p2 = p2;
	}

	public Point3f getP3() {
		return p3;
	}

	public void setP3(Point3f p3) {
		this.p3 = p3;
	}

}
